from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.openapi.docs import get_swagger_ui_html
import uvicorn
from routers import item_router, category_router

# 创建FastAPI应用 - 关闭默认docs
app = FastAPI(
    title="分层架构 CRUD API",
    description="使用分层架构构建的增删改查演示框架",
    version="2.0.0",
    docs_url=None,  # 关闭默认/docs
    redoc_url="/redoc"
)

# 挂载静态资源目录
app.mount("/static", StaticFiles(directory="static"), name="static")

# 自定义Swagger UI路由，使用本地静态资源
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    """自定义Swagger UI文档页面，使用本地静态资源"""
    return get_swagger_ui_html(
        openapi_url="/openapi.json",
        title="分层架构 CRUD API - 接口文档",
        swagger_js_url="/static/swagger-ui-bundle.js",
        swagger_css_url="/static/swagger-ui.css",
        swagger_favicon_url="https://fastapi.tiangolo.com/img/favicon.png"
    )

# 注册路由
app.include_router(item_router.router, prefix="/api/v1")
app.include_router(category_router.router, prefix="/api/v1")

@app.get("/")
async def root():
    """根路径，提供API信息"""
    return {
        "message": "欢迎使用分层架构 CRUD API",
        "version": "2.0.0",
        "architecture": "分层架构 (Layered Architecture)",
        "layers": [
            "表示层 (Presentation Layer) - API路由",
            "业务逻辑层 (Business Logic Layer) - 服务层",
            "数据访问层 (Data Access Layer) - 仓储层",
            "模型层 (Model Layer) - 数据模型"
        ],
        "documentation": {
            "swagger_ui": "/docs (使用本地静态资源)",
            "redoc": "/redoc"
        },
        "endpoints": {
            "商品管理": "/api/v1/items",
            "分类管理": "/api/v1/categories"
        }
    }

@app.get("/health")
async def health_check():
    """健康检查接口"""
    return {"status": "healthy", "message": "服务运行正常"}

if __name__ == "__main__":
    print("启动FastAPI服务器...")
    print("访问 http://localhost:8000 查看API")
    print("访问 http://localhost:8000/docs 查看API文档 (使用本地静态资源)")
    uvicorn.run(app, host="0.0.0.0", port=8000) 